"""
主程序入口
"""
import signal
import sys
import time
from typing import Optional

from common.config import settings
from common.database import DatabaseManager
from common.logger import create_logger
from common.redis import get_redis_service
from common.event_bus import init_event_bus, get_event_bus
from mqtt.consumer.mqtt_client import MQTTClient
from app.common.websocket_manager import websocket_manager

# 初始化日志
logging = create_logger("mqtt_main", settings.log_level, settings.log_file)


class MQTTApplication:
	"""MQTT应用程序主类"""

	def __init__(self):
		"""初始化应用"""
		self.mqtt_client: Optional[MQTTClient] = None
		self.event_bus = None
		self.shutdown_requested = False

		# 设置信号处理器
		signal.signal(signal.SIGINT, self.signal_handler)
		signal.signal(signal.SIGTERM, self.signal_handler)

	def signal_handler(self, sig, frame):
		"""信号处理函数"""
		signame = signal.Signals(sig).name
		print(f"\n收到关闭信号: {signame}")
		logging.info(f"收到关闭信号: {signame}")
		self.shutdown_requested = True
		# 移除 sys.exit(0)，由主循环自然退出

		# 关闭
		self.cleanup()
		sys.exit(0)

	def setup(self):
		"""初始化应用组件"""
		try:
			# 创建MQTT客户端
			self.mqtt_client = MQTTClient()
			logging.info("MQTT客户端初始化完成")

			# **新架构：初始化内存事件总线替代Outbox表**
			logging.info("正在初始化事件总线...")
			self.event_bus = init_event_bus(
				websocket_manager=websocket_manager,
				bus_type="memory",
				max_size=10000
			)
			logging.info("内存事件总线已启动")

			return True
		except Exception as e:
			logging.error(f"初始化失败: {str(e)}")
			return False

	def run(self):
		"""运行应用程序"""
		logging.info("启动MQTT数据采集服务...")

		if not self.setup():
			logging.error("应用初始化失败，退出程序")
			return

		try:
			# 启动MQTT客户端
			self.mqtt_client.run()

			# 主循环
			while not self.shutdown_requested:
				time.sleep(1)

		except KeyboardInterrupt:
			logging.info("收到键盘中断信号")
		except Exception as e:
			logging.error(f"应用程序运行错误: {str(e)}")
		finally:
			self.cleanup()

	def cleanup(self):
		"""清理资源"""
		logging.info("正在清理资源...")

		# 停止事件总线
		if self.event_bus:
			self.event_bus.stop()
			logging.info("事件总线已停止")

		if self.mqtt_client:
			self.mqtt_client.disconnect()
		logging.info("资源清理完成")


def main():
	# 创建并运行应用
	app = MQTTApplication()
	app.run()


if __name__ == "__main__":
	main()
